<template>
  <div id="history-work" class="app-container">
    <list-search-bar
      ref="searchbar"
      :search-rule="searchRule"
      @submit="getList($event, pageInfo)"
      @add="showEdit()"
      addText="新增栏目"
      @update:value="searchData = $event"
    />
    <zk-table
      ref="tablezk"
      sum-text="sum"
      index-text="#"
      :data="listData"
      :columns="listRule"
      :max-height="tableHeight"
      :table-height="tableHeight"
      :stripe="props.stripe"
      :border="props.border"
      :show-header="props.showHeader"
      :show-summary="props.showSummary"
      :show-row-hover="props.showRowHover"
      :show-index="props.showIndex"
      :tree-type="props.treeType"
      :is-fold="props.isFold"
      :expand-type="props.expandType"
      :selection-type="props.selectionType"
    >
      <template slot="likes" scope="scope">
        <!-- <el-button
          size="mini"
          @click="showEdit(scope.row, 'add')"
          type="primary"
          >添加</el-button
        > -->
        <el-button size="mini" @click="showEdit(scope.row)" type="primary"
          >编辑</el-button
        >
        <el-popconfirm
          class="mrl10"
          confirm-button-text="删除"
          confirm-button-type="danger"
          cancel-button-text="取消"
          icon="el-icon-info"
          icon-color="red"
          title="删除后该条信息将从列表中移除，请确认是否删除~"
          @onConfirm="remove(scope.row)"
        >
          <el-button slot="reference" type="danger" size="mini">
            删除
          </el-button>
        </el-popconfirm>
      </template>
    </zk-table>
    <div class="text-right size16 pd10">{{ pageInfo.total }}条</div>
    <!-- <pagination
      :page-sizes="[20]"
      :page-size="pageInfo.pageSize"
      :current-page="pageInfo.pageNo"
      :total="pageInfo.total"
      @pagination="getList(searchData, { ...pageInfo, pageNo: $event.page })"
    /> -->
    <back-to-top
      :visibility-height="300"
      :back-position="0"
      transition-name="fade"
    />
    <el-dialog
      :close-on-click-modal="false"
      width="500px"
      :visible.sync="editDialog"
      v-loading="editLoading"
      v-dialogDrag
      custom-class="widget-dialog widget-form widget-search center no-margin color-white black-bg2"
      title="详情"
    >
      <form-create
        v-model="editFormInstance"
        :value.sync="editData"
        :rule="editRule"
        :option="editOptions"
      />
      <template slot="footer">
        <el-button size="mini" type="primary" @click="update(editData)"
          >提交</el-button
        >
        <el-button size="mini" @click="editDialog = false">返回</el-button>
      </template>
    </el-dialog>
    <!-- 角色 -->
    <el-dialog
      :close-on-click-modal="false"
      width="600px"
      v-dialogDrag
      :visible.sync="roleDialog"
      v-loading="roleLoading"
      custom-class="widget-dialog widget-form center no-margin color-white black-bg2"
      title="分配角色"
    >
      <div class="widget-tree">
        <el-tree
          v-if="roleDialog"
          ref="roleNode"
          show-checkbox
          check-on-click-node
          :data="roleList"
          :props="roleProps"
          :render-after-expand="true"
          :expand-on-click-node="false"
          class="black-bg color-white"
          @check-change="roleChange"
          :default-checked-keys="roleCheck"
          node-key="id"
          check-strictly
        >
        </el-tree>
      </div>
      <template slot="footer">
        <el-button size="mini" type="primary" @click="roleUpdate"
          >提交</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  sysGetRoleList,
  knowledgePeizhiRole, //分类配置角色
  knowledgeGetRoleListByLevelId,
  knowledgeGetLanmuByMenuId as searchApi, //获取列表的api
  knowledgeInsertOrUpdateNode as updateApi, //更新、新增数据的api
  knowledgeDeleteNode as removeApi //删除数据的api
} from "@/api";
import { editRule, searchRule } from "@/formRules/system/WikiTypeRules";
import { editFormOptions, getData } from "@/formRules";
import cloneDeep from "lodash/cloneDeep";
import checkPermission from "@/utils/permission";
import { isDev } from "@/configurations.js";
import { translateDataToTree } from "@/utils/parentSon";
import mixin from "@/mixins/tableAutoHeight";
import { mapState } from "vuex";
import ZkTable from "vue-table-with-tree-grid";
export default {
  name: "HistoryWork",
  components: { ZkTable },
  configurations: {
    title: "栏目类",
    isDefault: true,
    icon: "el-icon-jilu",
    show: true,
    num: 3
  },
  mixins: [mixin],
  data() {
    return {
      listRule: editRule().filter(i => !i.hidden),
      editRule: editRule(),
      listData: [],
      searchRule: searchRule(),
      searchData: {}, //搜索表单数据
      editFormInstance: {},
      editData: {},
      editOptions: editFormOptions(),
      editDialog: false,
      editLoading: false,
      listLoading: false,
      pageInfo: {
        pageNo: 1,
        pageSize: 20,
        total: 0,
        pageNum: 0
      },
      columns: [],
      props: {
        stripe: false,
        border: false,
        showHeader: true,
        showSummary: false,
        showRowHover: true,
        showIndex: false,
        treeType: true,
        isFold: true,
        expandType: false,
        selectionType: false
      },
      roleList: [],
      roleDialog: false,
      roleLoading: false,
      roleCheck: [],
      roleProps: {
        children: "children",
        label: "roleName"
      },
      permissionList: [] //权限列表
    };
  },
  // 在路由导航进来之前检查权限
  beforeRouteEnter(from, to, next) {
    const permissionList = checkPermission(to.path);
    if (permissionList.length) {
      next(vm => {
        vm.permissionList = permissionList;
      });
      return;
    }
    next({
      name: "403"
    });
  },
  mounted() {
    this.getList(this.searchData, this.pageInfo);
  },
  computed: {
    layoutName() {
      return this.$route?.meta?.layout || "";
    },

    menuId() {
      if (!this.menuList?.length) return "";
      return this.menuList.find(e => e.name == this.layoutName)?.id;
    },
    ...mapState(["isAdmin", "userNow", "user"]),
    menuList() {
      return this.user?.menuList;
    },
    userId() {
      return this.userNow?.id;
    },
    userName() {
      return this.userNow?.userName;
    },
    // 根据获取的权限列表此处返回各个权限的显示与否
    permissions() {
      return ["edit", "remove", "add"].reduce((pre, cur) => {
        pre[cur] = isDev ? true : this.permissionList.includes(cur);
        return pre;
      }, {});
    }
  },
  methods: {
    /**
     * @name 获取角色列表
     */
    async getRoleList() {
      sysGetRoleList({ page: 1, size: 100, userName: this.userName }).then(
        ({ code, data }) => {
          if (code == 200) {
            this.roleList = data.list;
          }
        }
      );
    },
    /**
     * @name 获取分类对应角色
     */
    async getIdRole(row) {
      let { data, code, msg } = await knowledgeGetRoleListByLevelId({
        levelId: row.id
      });
      if (code == 200) {
        this.roleDialog = true;
        let treeData = data.map(e => e.roleId);
        if (treeData.length) {
          this.roleCheck = treeData;
        } else {
          this.roleCheck = [];
        }
      } else {
        this.$notified.error({
          message: msg
        });
      }
    },
    roleChange(data, checked, tree) {
      if (checked) {
        let list = this.$refs.treeNode.getCheckedKeys();
        this.roleCheck = list;

        //   this.editData.topoId = list.toString();
        //     this.$refs.roleNode.setCheckedNodes([data]);
      }
    },
    setRole(row) {
      this.editData = Object.assign({}, row);
      this.getIdRole(row);
    },
    async roleUpdate() {
      let list = this.$refs.roleNode.getCheckedKeys();
      let param = {
        levelId: this.editData.id,
        roleIdList: list
      };

      this.roleLoading = true;
      let { data, code, msg } = await knowledgePeizhiRole(param).finally(() => {
        this.roleLoading = false;
      });
      if (code == 200) {
        this.$notified.success({
          message: "角色分配成功!"
        });
        this.roleDialog = false;
        this.getList(this.searchData, this.pageInfo);
      } else {
        this.$notified.error({
          message: msg
        });
      }
    },
    /**
     * @name 查询列表
     * @param {Object} query 查询参数，一般为this.searchData
     * @param {Object} pageInfo 页面参数，包括pageSize和pageNo
     * @description 调用成功则刷新listData
     */
    async getList(query, pageInfo) {
      this.listLoading = true;
      const queryParam = {
        ...pageInfo,
        ...query,
        menuId: this.menuId
      };
      const { data } = await searchApi(queryParam).finally(() => {
        this.listLoading = false;
      });

      this.listData = translateDataToTree(data);
      console.log('document.getElementsByClassName("zk-table__body-wrapper")');
      console.log(document.getElementsByClassName("zk-table__body-wrapper"));
      document.getElementsByClassName(
        "zk-table__body-wrapper"
      )[0].style.maxHeight = this.tableHeight - 50 + "px";
      //   Object.assign(this.pageInfo, data);
      this.pageInfo.total = data.length;
    },
    /**
     * @name 编辑表单
     * @param {Object} row 表单数据，新增时为空
     * @description 调用成功打开表单对话框
     */
    showEdit(row, type) {
      console.log("row--------");
      console.log(row);
      if (!row) {
        this.editData = getData(editRule());
      } else {
        this.editData = cloneDeep(row);
        if (type == "add") {
          //添加节点
          this.editData = getData(editRule());
          this.editData.parentId = row.id;
        }
      }
      console.log(this.editData);
      this.editDialog = true;
    },
    /**
     * @name 更新数据
     * @param editData 编辑的数据体
     * @description 调用成功关闭对话框并且刷新表单
     */
    async update(editData) {
      if (!this.validation()) return;
      this.editLoading = true;
      let params = {
        ...editData,
        menuId: this.menuId
      };
      const { data, code } = await updateApi(params);
      if (code == 200) {
        this.editLoading = false;
        this.$notified.success({
          message: "更新数据成功"
        });
        this.getList(this.searchData, this.pageInfo);
        this.editDialog = false;
      }
    },
    /**
     * @name 表单验证
     * @description 如果有则在此处写入逻辑
     * @returns {Boolean} 表单验证结果
     */
    validation() {
      let satate = false;
      this.editFormInstance.validate((valid, fail) => {
        satate = valid;
      });
      // return true;
      return satate;
    },
    /**
     * @name 删除数据项
     * @description 成功后会刷新列表
     */
    async remove(row) {
      this.listLoading = true;
      let param = {
        nodeId: row.id,
        userId: this.userId
      };
      let { data, code, msg } = await removeApi(param).finally(() => {
        this.listLoading = false;
      });
      if (code == 200) {
        this.$notified.success({
          message: "删除成功"
        });
        this.getList(this.searchData, this.pageInfo);
      } else {
        this.$notified.error({
          message: msg
        });
      }
    },
    /**
     * @name 重置表单数据
     */
    reset() {
      this?.editFormInstance?.resetFields();
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~element-ui/packages/theme-chalk/src/common/var.scss";

#history-work {
  position: relative;
  overflow: hidden;
}
</style>
